from django.conf import settings
from django.db import models
from django.contrib.auth.models import AbstractUser
from itsdangerous import TimedJSONWebSignatureSerializer as S, BadSignature


# Create your models here.
from utils.models import BaseModel


class User(AbstractUser):
    """用户模型类"""
    # 父类中没有手机号，子类中扩展
    mobile = models.CharField(verbose_name='手机号', unique=True, max_length=11)

    email_active = models.BooleanField(default=False, verbose_name='邮箱验证状态')

    # 默认地址，优先显示默认地址
    default_address = models.ForeignKey('Address', related_name='users', null=True, blank=True,
                                        on_delete=models.SET_NULL, verbose_name='默认地址')

    class Meta:
        db_table = 'tb_users'
        verbose_name = '用户'
        verbose_name_plural = verbose_name

    def generic_email_token(self, email):
        serializer = S(settings.SECRET_KEY, 3600)

        token = serializer.dumps({'email': email, 'id': self.id})

        return 'http://www.meiduo.site:8080/success_verify_email.html?token=' + token.decode()

    # 因为不需要模型对象，所以把模型中的对象方法改为类方法，静态方法
    @staticmethod
    def check_verify_token(token):
        serializer = S(settings.SECRET_KEY, 3600)

        # 对token进行校验
        try:
            # result如果没有问题，就是前面的token字典
            result = serializer.loads(token)
        except BadSignature:
            return None
        else:
            # return result.get('id')
            try:
                id = result.get('id')
                # 相当于filter().filter()
                user = User.objects.get(id=id)
            except User.DoesNotExist:
                return None
            return user


# Address 模型要定义在User类后边
class Address(BaseModel):
    """
    用户地址
    """
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='addresses', verbose_name='用户')
    title = models.CharField(max_length=20, verbose_name='地址名称')
    receiver = models.CharField(max_length=20, verbose_name='收货人')
    # Address模型类中的外键指向Areas/models里面的Area，指明外键ForeignKey时，可以使用字符串 应用名.模型类名 来定义，自动去models中查找
    # related_name 在进行反向关联查询时使用的属性，如city = models.ForeignKey('areas.Area', related_name='city_addresses')表示可以通过Area对象.city_addresses属性获取所有相关的city数据。
    province = models.ForeignKey('areas.Area', on_delete=models.PROTECT, related_name='province_addresses', verbose_name='省')
    city = models.ForeignKey('areas.Area', on_delete=models.PROTECT, related_name='city_addresses', verbose_name='市')
    district = models.ForeignKey('areas.Area', on_delete=models.PROTECT, related_name='district_addresses', verbose_name='区')
    place = models.CharField(max_length=50, verbose_name='地址')
    mobile = models.CharField(max_length=11, verbose_name='手机')
    tel = models.CharField(max_length=20, null=True, blank=True, default='', verbose_name='固定电话')
    email = models.CharField(max_length=30, null=True, blank=True, default='', verbose_name='电子邮箱')
    is_deleted = models.BooleanField(default=False, verbose_name='逻辑删除')

    class Meta:
        db_table = 'tb_address'
        verbose_name = '用户地址'
        verbose_name_plural = verbose_name
        # ordering 表名在进行Address查询时，默认使用的排序方式
        ordering = ['-update_time']
